import { HttpErrorResponse } from '@angular/common/http';
import { Component, OnInit } from '@angular/core';
import { Title } from '@angular/platform-browser';
import { MemberVo } from 'src/app/model/member-vo';
import { BtnNaviSharedService } from 'src/app/services/btn-navi-shared.service';
import { MemberStorageService } from 'src/app/services/member-storage.service';
import { MemberService } from 'src/app/services/member.service';
import { UtilService } from 'src/app/services/util.service';

@Component({
  selector: 'app-personal-profile',
  templateUrl: './personal-profile.component.html',
  styles: [``]
})
export class PersonalProfileComponent implements OnInit {
  public curMember: MemberVo | null;
  public errorMessage: string = '';
  public profile: any = {
    member: 0,
    nickname: '',
    signature: '',
    token: '',
    ip: '127.0.0.1'
  };

  constructor(
    private title: Title,
    private memberStorage: MemberStorageService,
    private memberService: MemberService,
    private util: UtilService,
    private btnNaviSharedService: BtnNaviSharedService) {
    this.curMember = this.memberStorage.get();
    this.btnNaviSharedService.active(false);//不需要全局的导航
    this.profile.token = this.util.randomAlphaNumeric(8) || '123456';
    this.memberStorage.getIpCliente().subscribe(ipAddr=>this.profile.ip=ipAddr);
  }

  ngOnInit(): void {
    this.title.setTitle('个人中心:个性签名');
    this.profile.member = this.curMember?.id ?? 0;
    this.profile.nickname = this.curMember?.nickname ?? 'guest';
    this.profile.signature = this.curMember?.signature ?? '';
  }

  public updateProfile(submitBtn: HTMLButtonElement): void {
    submitBtn.disabled = true;
    submitBtn.setAttribute('value', '正在提交数据...');
    //
    this.memberService.editProfile(this.profile.member, this.profile.signature, this.profile.nickname, this.profile.token, this.profile.ip).subscribe({
      next: response => {
        //更新cache
        this.memberStorage.updateStorage(this.profile.member, { signature: this.profile.signature });
        this.util.alertSuccess('个性签名更新成功');
      },
      error: err => {
        if (err instanceof HttpErrorResponse) {
          if (err.error instanceof ErrorEvent) {
            this.errorMessage = err.error.message;
          } else {
            this.errorMessage = (err.status == 417) ? '个性签名更新失败' : err.error;
          }
        } else if (err instanceof Error) {
          this.errorMessage = err.message;
        } else { this.errorMessage = err; }
      },
      complete: () => {
        console.log('[PersonalProfile-CTL]Completed');
        //
        submitBtn.disabled = false;
        submitBtn.setAttribute('value', '提交更新');
      }
    });
  }
}
